package com.tanhua.server.serivce;

import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Sound;
import com.tanhua.domain.vo.SoundVo;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.dubbo.api.mongo.SoundApi;
import com.tanhua.server.interceptor.UserHolder;
import org.apache.dubbo.config.annotation.Reference;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;

@Service
public class SoundService {

    @Reference
    private SoundApi soundApi;
    @Autowired
    private FastFileStorageClient fastFileStorageClient;
    @Autowired
    private FdfsWebServer fdfsWebServer;
    @Reference
    private UserInfoApi userInfoApi;
    @Autowired
    private RedisTemplate redisTemplate;

    public ResponseEntity saveSound(MultipartFile soundFile) throws IOException {
        //使用fastdfs储存语音文件并返回URL
        StorePath storePath = fastFileStorageClient.uploadFile(soundFile.getInputStream(), soundFile.getSize(), "mp3", null);
        String url = fdfsWebServer.getWebServerUrl() + storePath.getFullPath();
        //根据id查找userinfo表查找用户信息
        UserInfo userInfo = userInfoApi.findById(UserHolder.getUserId());
        //创建Vo对象封装数据
        Sound sound = new Sound();
        sound.setId(ObjectId.get());
        sound.setUserId(UserHolder.getUserId());
        sound.setSoundUrl(url);
        sound.setState(0L);
        sound.setGender(userInfo.getGender());
        //通过api插入数据到表中
        soundApi.saveSound(sound);
        return ResponseEntity.ok(null);
    }

    public ResponseEntity getSound() {
        Long userId = UserHolder.getUserId();
        //获取登录用户信息
        UserInfo loginUser = userInfoApi.findById(userId);
        String gender = loginUser.getGender();
        //创建Vo类封装数据
        SoundVo soundVo = new SoundVo();
        String key = "RemainingTimes_" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "_" + userId;
        //通过本类的getRemainingTimes封装方法获取到用户剩余次数
        Integer times = getRemainingTimes();
        //再获取语音文件之前,先判断用户剩余次数是否大于1
        if (times > 0) {
            /**
             *   1.判断登录用户性别
             *   2.如果性别是男的,则返回的女性用户的语音,
             *   3.如果性别是女性,则返回的男性用户的语音.
             */
            if (gender.equals("man")) {
                //通过api从user_sound表中获取数据并封装到sound对象中,并返回
                Sound sound = soundApi.getSound(times, userId, "woman");
                //通过封装方法设置soundVo对象的成员变量
                setSoundVo(soundVo, key, times, sound);
            } else {
                //通过api从user_sound表中获取数据并封装到sound对象中,并返回
                Sound sound = soundApi.getSound(times, userId, "man");
                //通过封装方法设置soundVo对象的成员变量
                setSoundVo(soundVo, key, times, sound);
            }

        }
        return ResponseEntity.ok(soundVo);
    }

    private void setSoundVo(SoundVo soundVo, String key, Integer times, Sound sound) {
        if (sound != null) {
            soundVo.setSoundUrl(sound.getSoundUrl());
            soundVo.setRemainingTimes(times.intValue() - 1);
            redisTemplate.opsForValue().set(key, soundVo.getRemainingTimes());
            UserInfo userInfo = userInfoApi.findById(sound.getUserId());
            if (userInfo != null) {
                BeanUtils.copyProperties(userInfo, soundVo);
            }
        }
    }

    public Integer getRemainingTimes() {
        Long userId = UserHolder.getUserId();
        //根据登录id获取用户信息
        UserInfo userInfo = userInfoApi.findById(userId);
        Integer vipId = userInfo.getVipId();
        //设置一个key用于判断用户是否首次获取语音
        String key = "RemainingTimes_" + new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "_" + userId;
        Integer times = 0;
        //如果redis没有这个key,证明用户是首次获取语音,并根据用户是否为vip设置获取次数
        if (!redisTemplate.hasKey(key)) {
            if (vipId == 1) {
                times = 15;
            } else {
                times = 7;
            }
            redisTemplate.opsForValue().set(key, times, Duration.ofDays(1));
        }
        times = (Integer) redisTemplate.opsForValue().get(key);
        return times;
    }
}
